import datetime
import json
import random
import sys
from utils.hash import md5
from utils.tools import is_blank, process_error
from fastapi import APIRouter, Header, Depends
from pydantic import BaseModel
from models.requests import PageRequest, UserAdd, UserUpdate
from components.db import prisma
from fastapi_jwt_auth import AuthJWT


from prisma.errors import UniqueViolationError
from fastapi_jwt_auth.exceptions import MissingTokenError, JWTDecodeError

from utils.resp import BusinessException, resp_err, resp_json, resp_ok, resp_data
from utils.time import current_datetime

users_router = APIRouter()


@users_router.post("/user")
async def user_add(item: UserAdd, Authorize: AuthJWT = Depends()):
    try:
        Authorize.jwt_required()

        current_user = Authorize.get_jwt_subject()
        current_user = json.loads(current_user)

        if current_user['user_name'] != "root" and current_user['role'] != 0:
            return resp_err(f"admin can add user!")
        
        data = await prisma.user.create(data={
            "name": item.name,
            "password": md5(item.password),
            "role": 5,
            "createdAt": current_datetime(),
            "updatedAt": current_datetime()
        })

        return resp_data(data)

        # 原生查询
        # prisma.query_raw("SELECT * FROM user")
    
    #    user = await User.prisma().create(
    #         data={
    #             "name": item.name,
    #             "password": item.password,
    #             "role": 0,
    #             "createdAt": current_datetime(),
    #             "updatedAt": current_datetime()
    #         },
    #     )
    except Exception as e:
        process_error(e)





@users_router.get("/users")
async def users(Authorize: AuthJWT = Depends()):
    try:
        Authorize.jwt_required()

        res = await prisma.user.find_many(
            take=1000,
            order={
                "id": "desc"
            }
        )
        
        # delete password attr
        for item in res:
            delattr(item, "password")

        return resp_data(res)
    except Exception as e:
        process_error(e)




@users_router.delete("/user")
async def user_add(item: UserUpdate, Authorize: AuthJWT = Depends()):
    try:
        Authorize.jwt_required()

        current_user = Authorize.get_jwt_subject()
        current_user = json.loads(current_user)

        if current_user['user_name'] != "root" and current_user['role'] != 0:
            return resp_err(f"permission deny!")
        
        data = await prisma.user.delete(where={
            'id': item.id
        })
        return resp_data(data)
    except Exception as e:
        process_error(e)
